package com.lagou.listener;

import com.lagou.service.UserServiceImpl;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Description: ApplicationStartedListener.
 *
 * @author Wengy
 * @since JDK 1.8
 * @since 1.0.0
 */
@Component
public class ApplicationStartedListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                    .retryPolicy(retryPolicy).sessionTimeoutMs(1000 * 6).connectionTimeoutMs(1000 * 6).namespace("rpc").build();
            client.start();
            if(client.checkExists().forPath("/servers/server1")==null) {
                client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/servers/server1", "{\"host\": \"127.0.0.1\",\"port\": \"8990\"}".getBytes());
            }
            
            
            UserServiceImpl.startServer("127.0.0.1",8990);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
